/**
 * 
 */
package com.hayato.demo.dao;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.datanucleus.exceptions.NucleusObjectNotFoundException;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Transaction;
import com.hayato.demo.client.Info.OrderInfo;
import com.hayato.demo.client.Info.OrderProductInfo;
import com.hayato.demo.client.Info.ProductInfo;
import com.hayato.demo.utils.PMF;

/**
 *
 */
public class ProductDao {

	public List<ProductInfo> findAllProductInCategory2( Long category2Id ) {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query query = pm.newQuery( ProductInfo.class );
		query.setFilter( "category2Id == category2IdParam" );
		query.declareParameters( "Long category2IdParam" );

		try {
			return ( List<ProductInfo> ) query.execute( category2Id );
		} finally {
			query.closeAll();
		}
	}

	public List<ProductInfo> findProductByName( String productName ) {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		Query query = pm.newQuery( ProductInfo.class );
		query.setFilter( "product_name == productNameParam" );
		query.declareParameters( "String productNameParam" );

		//		String param = new StringBuilder().append( "%" ).append( productName )
		//				.append( "%" ).toString();

		try {
			return ( List<ProductInfo> ) query.execute( productName );
		} finally {
			query.closeAll();
		}
	}

	public List<ProductInfo> findListProduct( String[] listProductId ) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		
		ArrayList<ProductInfo> listProduct = new ArrayList<ProductInfo>(); 

		try {
			for( int i = 0; i < listProductId.length; i++ ) {
				listProduct.add( pm.getObjectById( ProductInfo.class, Long.parseLong( listProductId[i] ) ) );	
			}			
		} finally {
			pm.close();
		}
		
		return listProduct;
	}

	public ProductInfo findProductById( Long productId ) {
		PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			return pm.getObjectById( ProductInfo.class, productId );
		}catch( NucleusObjectNotFoundException e ) { 
			return null;
		} catch( Exception e ) {
			return null;
		} finally {
			pm.close();
		}
	}

	public void createAnOrder( OrderInfo order,
			List<OrderProductInfo> listOrderProduct ) {
		
		PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			OrderInfo insertedOrder = pm.makePersistent( order );
			
			for( int i = 0; i < listOrderProduct.size(); i++ ) {
				listOrderProduct.get( i ).setOrder_id( insertedOrder.getId() );
			}
			
			pm.makePersistentAll( listOrderProduct );
		} finally {
			pm.close();
		}
	}
}
